//
// Created by 叶璨铭 on 2022/5/17.
//
//#include "VocAnnotationXml.hpp"
#include "annotation_template.h"
#include "utils/filesystem.hpp"
#include <format>
#include <cassert>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <fmt/core.h>
#include <opencv2/opencv.hpp>
using cn::edu::SUSTech::YeCanming::Algs::Zip::utilities::filesystem::preorderTraversal;
namespace stdfs = std::filesystem;

int main() {
    auto resources = stdfs::path(CMAKE_PROJECT_DIR) / "resources";
    size_t dataSetSize = 0;
    if(!preorderTraversal(resources, [&](const stdfs::path &current_path) {
        std::clog<<"file travered"<<current_path<<std::endl;
        if (stdfs::is_regular_file(current_path)) {
            std::clog<<"is regular file"<<std::endl;
            auto extension = current_path.extension().generic_string();
            if (extension==".jpg"||extension==".png"){
                ++dataSetSize;
                auto parent = current_path.parent_path();
                auto filename = current_path.filename().generic_string();
                auto out = parent/(filename.substr(0, filename.size()-extension.size())+".xml");
//                std::clog<<"out is "<<out.generic_string()<<std::endl;
                std::fstream fileOut(out.generic_string(), std::ios::trunc | std::ios::out);
                assert(fileOut.is_open());
//                std::clog<<"fileout opened. "<<std::endl;
                cv::Mat mat = cv::imread(current_path.generic_string());
                assert(!mat.empty());
//                std::clog<<"fileout and image has opened. "<<std::endl;
                fileOut<<fmt::format(annotation_template,
                                       fmt::arg("filename", filename),
                                       fmt::arg("depth", mat.channels()),
                                       fmt::arg("width", mat.cols),
                                       fmt::arg("height", mat.rows)
                                       );
                assert(fileOut.good());
                fileOut.close();
//                std::clog<<"fileout is closed."<<std::endl;
            }
        }
//        auto parent = current_path.parent_path();
//        std::cout<<parent.filename()<<std::endl;
        return true;
    })){
        assert(false);
    }
    std::cout << "Label process has finished, totally " << dataSetSize << " images were labeled" << std::endl;
    return 0;
}